package com.jjwxc.jwjskandriod.fragment

import android.annotation.SuppressLint
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.SslErrorHandler
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.fragment.app.Fragment
import com.jjwxc.jwjskandriod.R
import com.jjwxc.jwjskandriod.config.Constants
import com.jjwxc.jwjskandriod.databinding.FragmentWebBinding
import com.jjwxc.jwjskandriod.readActivity.ReadActivity
import com.jjwxc.jwjskandriod.widget.dialog.MyDialogFragment

/**
 * 通用 WebFragment
 */
class WebFragment : Fragment() {
    private lateinit var dataBinding: FragmentWebBinding

    fun newInstance(url: String, type: Int? = -1): WebFragment {
        val fragment = WebFragment()
        val bundle = Bundle()
        bundle.putString("WEB_URL", url)

        if (type != -1) {
            bundle.putInt(Constants.WEB_DATA_TYPE, type!!)
        }

        fragment.arguments = bundle

        return fragment
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        dataBinding = FragmentWebBinding.inflate(inflater, container, false)

        afterCreate()

        return dataBinding.root
    }

    private fun afterCreate() {
        val url: String = arguments?.getString("WEB_URL").toString()
//        val name: String = arguments?.getString("WEB_NAME").toString()
//        val type: Int? = arguments?.getInt(Constants.WEB_DATA_TYPE, -1)
//        if (type == -1) {
            addWeb(url, false)
//        } else {
//            getAgreement(type!!)
//        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    fun addWeb(webUrl: String, isData: Boolean) {
        dataBinding.webview.settings.useWideViewPort = true //將圖片調整到適合webview的大小
        dataBinding.webview.settings.loadWithOverviewMode = true
        dataBinding.webview.settings.javaScriptEnabled = true
        dataBinding.webview.settings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
        dataBinding.webview.settings.domStorageEnabled = false
        dataBinding.webview.settings.setSupportZoom(false)
        dataBinding.webview.settings.builtInZoomControls = false
        if (isData) {
            dataBinding.webview.settings.defaultTextEncodingName = "UTF-8"
            dataBinding.webview.loadData(webUrl, "text/html", "UTF-8")
        } else {
//            dataBinding.webview.loadUrl(webUrl)
            dataBinding.webview.loadUrl(webUrl)
        }
        dataBinding.webview.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                //返回值是true的時候控制去WebView打開，為false調用系統瀏覽器或第三方瀏覽器
                view.loadUrl(url)
                return true
            }

            override fun onReceivedSslError(
                view: WebView,
                handler: SslErrorHandler,
                error: SslError
            ) {
                super.onReceivedSslError(view, handler, error)

                val myDialogFragment = MyDialogFragment(
                    context!!.getString(R.string.message_ssl_authentication_failed),
                    context!!.getString(R.string.cancel), context!!.getString(R.string.confirm)
                )

                // 取消按钮点击事件
                myDialogFragment.leftCallback = {
                    myDialogFragment.dismissDialog()
                    handler.cancel()
                    null
                }

                // 确认按钮点击事件
                myDialogFragment.rightCallback = {
                    myDialogFragment.dismissDialog()
                    if (handler != null) {
                        handler.proceed() //忽略證書的錯誤繼續加載頁面內容，不會變成空白頁面
                    }
                    null
                }

                // 设置窗口加载位置及动画模式
                myDialogFragment.setGravity(Gravity.CENTER)
                myDialogFragment.setAnimationStyle(R.style.PopupWindow)

                myDialogFragment.show(
                    (context as ReadActivity).supportFragmentManager,
                    "MyDialogFragment"
                )

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    dataBinding.webview.settings.mixedContentMode =
                        WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
                }
            }

            override fun onReceivedError(
                view: WebView,
                errorCode: Int,
                description: String,
                failingUrl: String
            ) {
                //                myProgressDialog.dismiss();
                super.onReceivedError(view, errorCode, description, failingUrl)
            }

            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                //                myProgressDialog.dismiss();
            }
        }
    }


    /*private fun getAgreement(type: Int) {
        (activity as BaseActivity).post(
            Url.getAgreement, null,
            AgreementResponse::class.java, object : FFNetWorkCallBack<AgreementResponse?>() {
                override fun onSuccess(response: AgreementResponse?) {
                    addWeb(response?.data!!.content!!, true)
                }

                override fun onFail(response: AgreementResponse?): Boolean {
                    return false
                }
            }, "{\"type\": $type}"
        )
    }*/
}